// 创建悬浮球
function createFloatingBall() {
  const ball = document.createElement('div');
  ball.className = 'floating-ball';
  ball.innerHTML = 'ST';
  document.body.appendChild(ball);
  
  // 添加点击事件
  ball.addEventListener('click', (e) => {
    e.stopPropagation(); // 阻止事件冒泡
    const settingsPanel = document.querySelector('.settings-panel');
    if (settingsPanel) {
      closeSettings();
    } else {
      openSettings();
    }
  });
  
  // 添加拖拽功能
  let isDragging = false;
  let currentX;
  let currentY;
  let initialX;
  let initialY;
  let xOffset = 0;
  let yOffset = 0;
  
  ball.addEventListener('mousedown', dragStart);
  
  function dragStart(e) {
    initialX = e.clientX - xOffset;
    initialY = e.clientY - yOffset;
    
    if (e.target === ball) {
      isDragging = true;
    }
  }
  
  document.addEventListener('mousemove', drag);
  document.addEventListener('mouseup', dragEnd);
  
  function drag(e) {
    if (isDragging) {
      e.preventDefault();
      currentX = e.clientX - initialX;
      currentY = e.clientY - initialY;
      
      xOffset = currentX;
      yOffset = currentY;
      
      setTranslate(currentX, currentY, ball);
    }
  }
  
  function setTranslate(xPos, yPos, el) {
    el.style.transform = `translate3d(${xPos}px, ${yPos}px, 0)`;
  }
  
  function dragEnd() {
    initialX = currentX;
    initialY = currentY;
    isDragging = false;
  }
  
  return ball;
}

// 创建股票信息面板
function createStockPanel() {
  const panel = document.createElement('div');
  panel.className = 'stock-panel';
  
  // 添加设置按钮
  const settingsBtn = document.createElement('button');
  settingsBtn.className = 'settings-btn';
  settingsBtn.innerHTML = '设置';
  settingsBtn.onclick = showSettings;
  
  // 添加刷新按钮
  const refreshBtn = document.createElement('button');
  refreshBtn.className = 'refresh-btn';
  refreshBtn.innerHTML = '刷新';
  refreshBtn.onclick = () => refreshStockData();
  
  panel.appendChild(settingsBtn);
  panel.appendChild(refreshBtn);
  
  return panel;
}

// 创建股票代码提示列表
let stockSuggestions = [];
let currentSuggestionIndex = -1;

// 获取股票代码建议
async function getStockSuggestions(input) {
  if (!input) return [];
  
  // 这里使用新浪财经的API获取股票列表
  try {
    const response = await fetch('https://hq.sinajs.cn/list=sh000001,sz399001');
    const text = await response.text();
    const stocks = text.split('\n').filter(line => line.includes('var hq_str_'));
    
    return stocks
      .map(line => {
        const code = line.match(/hq_str_(sh|sz)\d{6}/)[0].replace('hq_str_', '');
        const name = line.split('=')[1].split(',')[0].replace(/"/g, '');
        return { code, name };
      })
      .filter(stock => 
        stock.code.toLowerCase().includes(input.toLowerCase()) ||
        stock.name.includes(input)
      )
      .slice(0, 5); // 最多显示5个建议
  } catch (error) {
    console.error('获取股票建议失败:', error);
    return [];
  }
}

// 显示股票代码建议
function showSuggestions(suggestions) {
  const input = document.getElementById('stockCode');
  let suggestionList = document.getElementById('stockSuggestions');
  
  if (!suggestionList) {
    suggestionList = document.createElement('div');
    suggestionList.id = 'stockSuggestions';
    suggestionList.className = 'stock-suggestions';
    input.parentNode.appendChild(suggestionList);
  }
  
  if (suggestions.length === 0) {
    document.getElementById('stockSuggestions')?.remove();
    return;
  }
  
  suggestionList.innerHTML = suggestions.map((stock, index) => `
    <div class="suggestion-item ${index === currentSuggestionIndex ? 'active' : ''}" 
         onclick="selectSuggestion('${stock.code}')">
      <span class="suggestion-code">${stock.code}</span>
      <span class="suggestion-name">${stock.name}</span>
    </div>
  `).join('');
}

// 选择建议的股票代码
function selectSuggestion(code) {
  const input = document.getElementById('stockCode');
  input.value = code;
  input.focus();
  document.getElementById('stockSuggestions')?.remove();
  currentSuggestionIndex = -1;
}

// 处理键盘导航
function handleKeyNavigation(e) {
  const suggestions = document.querySelectorAll('.suggestion-item');
  if (suggestions.length === 0) return;
  
  switch (e.key) {
    case 'ArrowDown':
      e.preventDefault();
      currentSuggestionIndex = (currentSuggestionIndex + 1) % suggestions.length;
      break;
    case 'ArrowUp':
      e.preventDefault();
      currentSuggestionIndex = (currentSuggestionIndex - 1 + suggestions.length) % suggestions.length;
      break;
    case 'Enter':
      e.preventDefault();
      if (currentSuggestionIndex >= 0) {
        const code = suggestions[currentSuggestionIndex].querySelector('.suggestion-code').textContent;
        selectSuggestion(code);
      } else {
        addStock();
      }
      break;
    case 'Escape':
      document.getElementById('stockSuggestions')?.remove();
      currentSuggestionIndex = -1;
      break;
  }
  
  showSuggestions(stockSuggestions);
}

// 批量导入股票
async function importStocks() {
  const textarea = document.createElement('textarea');
  textarea.className = 'import-textarea';
  textarea.placeholder = '请输入股票代码，每行一个\n例如：\nsh000001\nsz399001';
  
  const importPanel = document.createElement('div');
  importPanel.className = 'import-panel';
  importPanel.innerHTML = `
    <h3>批量导入股票</h3>
    <div class="import-content"></div>
    <div class="import-actions">
      <button class="cancel-btn" onclick="closeImportPanel()">取消</button>
      <button class="import-btn" onclick="confirmImport()">导入</button>
    </div>
  `;
  
  importPanel.querySelector('.import-content').appendChild(textarea);
  document.body.appendChild(importPanel);
  textarea.focus();
}

// 确认导入
async function confirmImport() {
  const textarea = document.querySelector('.import-textarea');
  const codes = textarea.value
    .split('\n')
    .map(code => code.trim().toLowerCase())
    .filter(code => code && validateStockCode(code));
  
  if (codes.length === 0) {
    alert('没有有效的股票代码');
    return;
  }
  
  const { stocks } = await getStoredStocks();
  const newStocks = [...new Set([...stocks, ...codes])];
  
  await chrome.storage.local.set({ stocks: newStocks });
  loadStockList();
  refreshStockData();
  closeImportPanel();
}

// 关闭导入面板
function closeImportPanel() {
  const importPanel = document.querySelector('.import-panel');
  if (importPanel) {
    importPanel.remove();
  }
}

// 验证股票代码格式
function validateStockCode(code) {
  // 只验证6位数字
  const pattern = /^\d{6}$/;
  return pattern.test(code);
}

// 获取股票前缀
function getStockPrefix(code) {
  // 上海主板：600、601、603、605开头
  // 上海科创板：688开头
  // 深圳主板：000开头
  // 深圳创业板：300、301开头
  // 深圳中小板：002开头
  const prefix = code.substring(0, 3);
  if (['600', '601', '603', '605', '688'].includes(prefix)) {
    return 'sh';
  } else if (['000', '002', '300', '301'].includes(prefix)) {
    return 'sz';
  }
  return '';
}

// 获取股票名称
async function getStockName(code) {
  try {
    // 转换股票代码格式为东方财富格式
    const secid = code.startsWith('sh') ? `1.${code.slice(2)}` : `0.${code.slice(2)}`;
    const response = await fetch(`https://push2.eastmoney.com/api/qt/stock/get?secid=${secid}&fields=f58,f57`);
    const data = await response.json();
    
    if (!data.data || !data.data.f58) {
      throw new Error('获取股票名称失败');
    }
    
    return data.data.f58;
  } catch (error) {
    console.error('获取股票名称失败:', error);
    return code;
  }
}

// 获取存储的股票列表
async function getStoredStocks() {
  try {
    const result = await chrome.storage.local.get(['stocks', 'stockSettings']);
    return {
      stocks: result.stocks || ['sh000001', 'sz399001'],
      settings: result.stockSettings || {}
    };
  } catch (error) {
    console.error('获取存储数据失败:', error);
    // 如果是扩展上下文失效，刷新页面
    if (error.message.includes('Extension context invalidated')) {
      window.location.reload();
      return;
    }
    // 返回默认值
    return {
      stocks: ['sh000001', 'sz399001'],
      settings: {}
    };
  }
}

// 获取股票数据
async function fetchStockData(stockCodes) {
  try {
    const promises = stockCodes.map(async code => {
      try {
        // 转换股票代码格式为东方财富格式
        const secid = code.startsWith('sh') ? `1.${code.slice(2)}` : `0.${code.slice(2)}`;
        const response = await fetch(`https://push2.eastmoney.com/api/qt/stock/get?secid=${secid}&fields=f59,f43,f57,f58,f169,f170,f46,f44,f51,f168,f47,f164,f163,f116,f60,f45,f52,f50,f48,f167,f117,f71,f161,f49,f530,f135,f136,f137,f138,f139,f141,f142,f144,f145,f147,f148,f140,f143,f146,f149,f55,f62,f162,f92,f173,f104,f105,f84,f85,f183,f184,f185,f186,f187,f188,f189,f190,f191,f192,f107,f111,f86,f177,f78,f110,f262,f263,f264,f267,f268,f250,f251,f252,f253,f254,f255,f256,f257,f258,f266,f269,f270,f271,f273,f274,f275,f127,f199,f128,f193,f196,f194,f195,f197,f80,f280,f281,f282,f284,f285,f286,f287,f292`);
        const data = await response.json();
        
        if (!data.data) {
          throw new Error('数据格式错误');
        }
        
        const quote = data.data;
        console.log(quote);
        const settings = await getStockSettings(code);
        const currentPrice = quote.f43 / 100; // 当前价
        const preClose = quote.f60 / 100; // 昨收
        const change = currentPrice - preClose; // 涨跌额
        const changePercent = (change / preClose * 100).toFixed(2); // 涨跌幅
        
        // 计算持仓盈亏
        const holdingAmount = settings.costPrice * (settings.shares || 0); // 持仓金额
        const marketValue = currentPrice * (settings.shares || 0); // 市值
        const profitAmount = marketValue - holdingAmount; // 盈亏金额
        const profitPercent = holdingAmount ? ((marketValue / holdingAmount - 1) * 100).toFixed(2) : '0.00'; // 盈亏比例
        
        return {
          code,
          name: quote.f58,
          price: currentPrice,
          change,
          changePercent,
          volume: quote.f47 * 100, // 成交量
          amount: quote.f48 * 10000, // 成交额
          costPrice: settings.costPrice || 0,
          shares: settings.shares || 0,
          holdingAmount,
          marketValue,
          profitAmount,
          profitPercent
        };
      } catch (error) {
        console.error(`获取股票 ${code} 数据失败:`, error);
        return {
          code,
          name: '获取失败',
          price: 0,
          change: 0,
          changePercent: '0.00',
          volume: 0,
          amount: 0,
          costPrice: 0,
          shares: 0,
          holdingAmount: 0,
          marketValue: 0,
          profitAmount: 0,
          profitPercent: '0.00'
        };
      }
    });
    return await Promise.all(promises);
  } catch (error) {
    console.error('获取股票数据失败:', error);
    return [];
  }
}

// 保存股票设置
async function saveStockSettings(code, settings) {
  const { stocks, settings: currentSettings } = await getStoredStocks();
  currentSettings[code] = settings;
  await chrome.storage.local.set({ stockSettings: currentSettings });
}

// 获取股票设置
async function getStockSettings(code) {
  const { settings } = await getStoredStocks();
  return settings[code] || {
    costPrice: 0,
    profitTarget: 0,
    lossTarget: 0,
    soundEnabled: true,
    alertFrequency: 'once', // once, every
    lastAlertTime: 0
  };
}

// 创建股票设置面板
function createStockSettingsPanel(code, name) {
  const settingsPanel = document.createElement('div');
  settingsPanel.className = 'stock-settings-panel';
  settingsPanel.innerHTML = `
    <div class="settings-content">
      <h3>${name} (${code})</h3>
      <div class="settings-form">
        <div class="form-group">
          <label>成本价：</label>
          <input type="number" id="costPrice" step="0.01" min="0" placeholder="请输入成本价">
        </div>
        <div class="form-group">
          <label>持仓数量：</label>
          <div class="shares-input">
            <input type="number" id="shares" step="1" min="0" placeholder="请输入持仓数量">
            <span class="unit">手</span>
          </div>
          <div class="shares-tip">1手 = 100股</div>
        </div>
        <div class="form-actions">
          <button class="save-btn" data-code="${code}">保存</button>
          <button class="cancel-btn">取消</button>
        </div>
      </div>
    </div>
  `;

  // 添加事件监听器
  const saveBtn = settingsPanel.querySelector('.save-btn');
  const cancelBtn = settingsPanel.querySelector('.cancel-btn');
  
  saveBtn.addEventListener('click', () => {
    const costPrice = parseFloat(settingsPanel.querySelector('#costPrice').value) || 0;
    const shares = parseInt(settingsPanel.querySelector('#shares').value) || 0;
    
    // 将手数转换为股数
    saveStockSettings(code, {
      costPrice,
      shares: shares * 100 // 转换为股数
    });
    
    closeStockSettings();
    loadStockList();
  });
  
  cancelBtn.addEventListener('click', closeStockSettings);

  return settingsPanel;
}

// 显示股票设置面板
async function showStockSettings(code, name) {
  closeStockSettings(); // 先关闭可能存在的设置面板
  
  const settings = await getStockSettings(code);
  const settingsPanel = createStockSettingsPanel(code, name);
  document.body.appendChild(settingsPanel);
  
  // 填充现有设置，将股数转换为手数
  document.getElementById('costPrice').value = settings.costPrice || '';
  document.getElementById('shares').value = settings.shares ? (settings.shares / 100) : '';
}

// 关闭股票设置面板
function closeStockSettings() {
  const settingsPanel = document.querySelector('.stock-settings-panel');
  if (settingsPanel) {
    settingsPanel.remove();
  }
}

// 检查止盈止损
function checkPriceAlerts(stock, settings) {
  if (!settings.costPrice) return null;
  
  const currentPrice = stock.price;
  const profitPercent = ((currentPrice - settings.costPrice) / settings.costPrice * 100).toFixed(2);
  const now = Date.now();
  
  // 检查是否需要提醒
  if (settings.alertFrequency === 'once' && settings.lastAlertTime > 0) {
    return null;
  }
  
  if (settings.profitTarget && currentPrice >= settings.profitTarget) {
    // 播放声音
    if (settings.soundEnabled) {
      profitSound.play().catch(console.error);
    }
    
    // 更新最后提醒时间
    settings.lastAlertTime = now;
    
    return {
      type: 'profit',
      message: `${stock.name} 已达到止盈价 ${settings.profitTarget}，当前涨幅 ${profitPercent}%`
    };
  }
  
  if (settings.lossTarget && currentPrice <= settings.lossTarget) {
    // 播放声音
    if (settings.soundEnabled) {
      lossSound.play().catch(console.error);
    }
    
    // 更新最后提醒时间
    settings.lastAlertTime = now;
    
    return {
      type: 'loss',
      message: `${stock.name} 已达到止损价 ${settings.lossTarget}，当前跌幅 ${profitPercent}%`
    };
  }
  
  return null;
}

// 显示提醒
function showAlert(message, type) {
  const alert = document.createElement('div');
  alert.className = `stock-alert ${type}`;
  
  // 添加图标
  const icon = document.createElement('span');
  icon.className = 'alert-icon';
  icon.innerHTML = type === 'profit' ? '📈' : '📉';
  
  // 添加消息
  const text = document.createElement('span');
  text.className = 'alert-message';
  text.textContent = message;
  
  // 添加关闭按钮
  const closeBtn = document.createElement('button');
  closeBtn.className = 'alert-close';
  closeBtn.innerHTML = '×';
  closeBtn.onclick = () => alert.remove();
  
  alert.appendChild(icon);
  alert.appendChild(text);
  alert.appendChild(closeBtn);
  
  document.body.appendChild(alert);
  
  // 5秒后自动关闭
  setTimeout(() => {
    alert.classList.add('fade-out');
    setTimeout(() => alert.remove(), 300);
  }, 5000);
}

// 更新股票面板内容
async function updateStockPanel(panel, stocks) {
  const { settings } = await getStoredStocks();
  
  const stockList = await Promise.all(stocks.map(async stock => {
    const stockSettings = settings[stock.code] || {};
    const alert = checkPriceAlerts(stock, stockSettings);
    
    if (alert) {
      showAlert(alert.message, alert.type);
    }
    
    const profitPercent = stockSettings.costPrice ? 
      ((stock.price - stockSettings.costPrice) / stockSettings.costPrice * 100).toFixed(2) : null;
    
    return `
      <div class="stock-item ${profitPercent ? (profitPercent >= 0 ? 'profit' : 'loss') : ''}">
        <div class="stock-header">
          <span class="stock-name">${stock.name}</span>
          <div class="stock-actions">
            <button  onclick="showStockSettings('${stock.code}', '${stock.name}')" title="设置">
            </button>
            <span class="stock-code">${stock.code}</span>
          </div>
        </div>
        <div class="stock-info">
          <div class="stock-price ${profitPercent ? (profitPercent >= 0 ? 'up' : 'down') : ''}">${stock.price.toFixed(2)} <span class="stock-change">${stock.change >= 0 ? '+' : ''}${stock.change.toFixed(2)} (${stock.changePercent})</span></div>
          <div class="stock-details">
            <div>成本: ${stock.costPrice.toFixed(2)}</div>
            <div>持仓: ${(stock.shares / 100).toFixed(0)}手</div>
            <div>市值: ${(stock.marketValue / 100).toFixed(2)}</div>
          </div>
          <div class="profit-info ${stock.shares === 0 ? 'neutral' : (stock.profitAmount >= 0 ? 'up' : 'down')}">
            盈利：${stock.profitAmount >= 0 ? '+' : ''}${stock.profitAmount.toFixed(2)} (${stock.profitPercent}%)
          </div>
        </div>
      </div>
    `;
  }));
  
  const content = panel.querySelector('.stock-content');
  if (content) {
    content.innerHTML = stockList.join('');
  } else {
    const newContent = document.createElement('div');
    newContent.className = 'stock-content';
    newContent.innerHTML = stockList.join('');
    panel.appendChild(newContent);
  }
}

// 判断是否在交易时间内
function isTradingTime() {
  const now = new Date();
  const hour = now.getHours();
  const minute = now.getMinutes();
  const day = now.getDay();
  
  // 周末休市
  if (day === 0 || day === 6) {
    return false;
  }
  
  // 上午交易时间 9:30-11:30
  if ((hour === 9 && minute >= 30) || (hour === 10) || (hour === 11 && minute <= 30)) {
    return true;
  }
  
  // 下午交易时间 13:00-15:00
  if ((hour === 13) || (hour === 14) || (hour === 15 && minute === 0)) {
    return true;
  }
  
  return false;
}

// 格式化时间
function formatTime(date) {
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  return `${hours}:${minutes}:${seconds}`;
}

// 格式化数字为逗号分隔法
function formatNumber(num) {
  return num.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
}

// 显示设置面板
function openSettings() {
  // 移除可能存在的旧面板
  closeSettings();
  
  // 创建遮罩层
  const overlay = document.createElement('div');
  overlay.className = 'settings-overlay';
  overlay.onclick = closeSettings;
  document.body.appendChild(overlay);
  
  // 创建设置面板
  const settingsPanel = document.createElement('div');
  settingsPanel.className = 'settings-panel';
  settingsPanel.innerHTML = `
    <div class="settings-content">
      <h3>STOCK</h3>
      <div class="stock-input">
        <input type="text" id="stockCode" placeholder="输入6位股票代码" maxlength="6" autocomplete="off">
        <button id="addStockBtn">添加</button>
        <button id="kimiAiBtn">KIMI AI</button>
        <div class="stock-summary">
          <div class="summary-item">
            <span class="summary-label">总成本</span>
            <span class="summary-value" id="totalCost">0.00</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">总盈利</span>
            <span class="summary-value" id="totalProfit">0.00 <span class="summary-percent">0.00%</span></span>
          </div>
        </div>
      </div>
      <div class="refresh-status">
        <span class="last-refresh">最后刷新：--:--:--</span>
        <span class="market-status"></span>
      </div>
      <div id="stockList"></div>
    </div>
  `;
  
  // 先添加面板，再加载数据
  document.body.appendChild(settingsPanel);
  
  // 加载数据
  loadStockList();
  
  // 添加输入监听
  const input = settingsPanel.querySelector('#stockCode');
  const addButton = settingsPanel.querySelector('#addStockBtn');
  
  // 限制只能输入数字
  input.addEventListener('input', (e) => {
    e.target.value = e.target.value.replace(/[^\d]/g, '');
  });
  
  // 添加按钮点击事件
  addButton.addEventListener('click', () => addStock());
  
  // 输入框回车事件
  input.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      addStock();
    }
  });

  // 添加遮罩层点击事件
  overlay.addEventListener('click', (e) => {
    if (e.target === overlay) {
      closeSettings();
    }
  });
  
  // 更新刷新状态
  updateRefreshStatus();
  
  // 初始化KIMI AI按钮
  initKimiAiButton();
}

// 关闭设置面板
function closeSettings() {
  const settingsPanel = document.querySelector('.settings-panel');
  const overlay = document.querySelector('.settings-overlay');
  if (settingsPanel) {
    settingsPanel.remove();
  }
  if (overlay) {
    overlay.remove();
  }
}

// 自动刷新相关变量
let refreshTimer = null;
let isClosedMarketRefreshed = false;

// 开始自动刷新
function startAutoRefresh() {
  stopAutoRefresh(); // 先停止可能存在的刷新
  isClosedMarketRefreshed = false; // 重置休市刷新标志
  
  refreshTimer = setInterval(async () => {
    if (isTradingTime()) {
      const { stocks } = await getStoredStocks();
      const stockData = await fetchStockData(stocks);
      const stockList = document.getElementById('stockList');
      if (stockList) {
        loadStockList();
      }
      updateRefreshStatus();
    } else if (!isClosedMarketRefreshed) {
      // 休市时只刷新一次
      const { stocks } = await getStoredStocks();
      const stockData = await fetchStockData(stocks);
      const stockList = document.getElementById('stockList');
      if (stockList) {
        loadStockList();
      }
      updateRefreshStatus();
      isClosedMarketRefreshed = true;
    }
  }, 2000); // 每2秒刷新一次
}

// 停止自动刷新
function stopAutoRefresh() {
  if (refreshTimer) {
    clearInterval(refreshTimer);
    refreshTimer = null;
  }
}

// 更新刷新状态
function updateRefreshStatus() {
  const lastRefresh = document.querySelector('.last-refresh');
  const marketStatus = document.querySelector('.market-status');
  
  if (lastRefresh) {
    lastRefresh.textContent = `最后刷新：${formatTime(new Date())}`;
  }
  
  if (marketStatus) {
    if (isTradingTime()) {
      marketStatus.textContent = '交易中';
      marketStatus.className = 'market-status trading';
    } else {
      marketStatus.textContent = '休市中';
      marketStatus.className = 'market-status closed';
      if (isClosedMarketRefreshed) {
        marketStatus.textContent = '休市中（已更新）';
      }
    }
  }
}

// 刷新股票数据
async function refreshStockData() {
  if (!isTradingTime()) {
    console.log('当前为休市时间，不更新数据');
    return;
  }
  
  const { stocks } = await getStoredStocks();
  const stockData = await fetchStockData(stocks);
  const stockList = document.getElementById('stockList');
  if (stockList) {
    loadStockList();
  }
  updateRefreshStatus();
}

// 初始化
function init() {
  // 创建悬浮球
  const ball = createFloatingBall();

  
  // 加载股票列表
  loadStockList();
  
  // 开始自动刷新
  startAutoRefresh();
  
  // 监听来自background的消息
  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.type === 'refreshStocks') {
      refreshStockData();
    }
  });
}

// 页面加载完成后初始化
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', init);
} else {
  init();
}

// 将函数添加到全局作用域
window.removeStock = removeStock;
window.showStockSettings = showStockSettings;
window.closeStockSettings = closeStockSettings;
window.saveStockSettings = saveStockSettings;
window.refreshStockData = refreshStockData;

// 添加股票
async function addStock() {
  try {
    const input = document.getElementById('stockCode');
    const code = input.value.trim();
    
    if (!code) {
      alert('请输入股票代码');
      return;
    }
    
    if (!validateStockCode(code)) {
      alert('请输入6位数字股票代码');
      return;
    }
    
    const prefix = getStockPrefix(code);
    if (!prefix) {
      alert('不支持的股票代码格式');
      return;
    }
    
    const fullCode = `${prefix}${code}`;
    const { stocks } = await getStoredStocks();
    
    if (!stocks.includes(fullCode)) {
      const stockName = await getStockName(fullCode);
      if (!stockName || stockName === fullCode) {
        alert('无法获取股票信息，请检查股票代码是否正确');
        return;
      }
      
      const newStocks = [...stocks, fullCode];
      await chrome.storage.local.set({ stocks: newStocks });
      
      // 清空输入框并保持焦点
      input.value = '';
      input.focus();
      
      // 重新加载列表
      loadStockList();
    } else {
      alert('该股票已在列表中');
    }
  } catch (error) {
    console.error('添加股票失败:', error);
    // 如果是扩展上下文失效，刷新页面
    if (error.message.includes('Extension context invalidated')) {
      window.location.reload();
      return;
    }
    alert('添加股票失败，请刷新页面后重试');
  }
}

// 加载股票列表
async function loadStockList() {
  const stockList = document.getElementById('stockList');
  if (!stockList) return;
  
  const { stocks } = await getStoredStocks();
  const stockData = await fetchStockData(stocks);
  
  if (stocks.length === 0) {
    stockList.innerHTML = '<div class="stock-list-item">暂无股票，请添加</div>';
    return;
  }

  // 计算总成本和总盈利
  let totalCost = 0;
  let totalProfit = 0;
  
  stockData.forEach(stock => {
    if (stock.shares > 0) {
      totalCost += stock.price * stock.shares;
      totalProfit += stock.profitAmount;
    }
  });

  // 更新总成本和总盈利显示
  const totalCostElement = document.getElementById('totalCost');
  const totalProfitElement = document.getElementById('totalProfit');
  
  if (totalCostElement) {
    totalCostElement.textContent = formatNumber(totalCost);
  }
  
  if (totalProfitElement) {
    totalProfitElement.textContent = (totalProfit >= 0 ? '+' : '') + formatNumber(totalProfit);
    totalProfitElement.className = `summary-value ${totalProfit > 0 ? 'profit' : (totalProfit < 0 ? 'loss' : 'neutral')}`;
  }

  // 将股票分为已设置持仓和未设置持仓两组
  const stocksWithPosition = stockData.filter(stock => stock.shares > 0);
  const stocksWithoutPosition = stockData.filter(stock => stock.shares === 0);

  // 对每组按涨幅倒序排序
  stocksWithPosition.sort((a, b) => parseFloat(b.changePercent) - parseFloat(a.changePercent));
  stocksWithoutPosition.sort((a, b) => parseFloat(b.changePercent) - parseFloat(a.changePercent));

  // 合并两组股票
  const sortedStockData = [...stocksWithPosition, ...stocksWithoutPosition];
  
  // 创建网格布局
  stockList.innerHTML = `
    <div class="stock-list-container">
      ${sortedStockData.map(stock => {
        const priceChangeClass = stock.change > 0 ? 'up' : (stock.change < 0 ? 'down' : 'neutral');
        return generateStockCard(stock, priceChangeClass);
      }).join('')}
    </div>
  `;

  // 生成股票卡片
  function generateStockCard(stock, priceChangeClass) {
    // 获取量化分析结果
    const analysis = analyzeStock(stock);
    const actionClass = analysis.action;
    const actionIcon = getActionIcon(analysis.action);
    const actionText = getActionText(analysis.action);
    
    // 存储分析结果到股票对象中，以便点击量化分析按钮时使用
    stock.quantitativeAnalysis = analysis;
    
    return `
      <div class="stock-list-item">
        <div class="stock-info">
          <div class="stock-header">
            <div class="stock-name">
              <strong>${stock.name}</strong>
              <span class="stock-code">${stock.code}</span>
            </div>
            <div class="stock-actions">
              <a href="javascript:void(0)" class="action-link detail-btn" onclick="window.open('https://quote.eastmoney.com/concept/${stock.code}.html')">详情</a>
              <a href="javascript:void(0)" class="action-link settings-btn" data-code="${stock.code}" data-name="${stock.name}">设置</a>
              <a href="javascript:void(0)" class="action-link delete-btn" data-code="${stock.code}">删除</a>
              <a href="javascript:void(0)" class="action-link quant-btn" data-code="${stock.code}" data-name="${stock.name}">量化分析</a>
            </div>
          </div>
          <div class="stock-price ${priceChangeClass}">
            ${formatNumber(stock.price)}
            <span class="stock-change">${stock.change >= 0 ? '+' : ''}${formatNumber(stock.change)} (${stock.changePercent}%)</span>
            <span class="quant-indicator ${actionClass}" title="${analysis.message}">
              ${actionIcon} ${actionText}
            </span>
          </div>
          <div class="stock-details">
            <div class="detail-item">成本: ${formatNumber(stock.costPrice)}</div>
            <div class="detail-item">持仓: ${(stock.shares / 100).toFixed(0)}手</div>
            <div class="detail-item">市值: ${formatNumber(stock.price * stock.shares)}</div>
          </div>
          <div class="profit-info ${stock.shares === 0 ? 'neutral' : (stock.profitAmount >= 0 ? 'up' : 'down')}">
            盈利：${stock.profitAmount >= 0 ? '+' : ''}${formatNumber(stock.profitAmount)} (${stock.profitPercent}%)
          </div>
        </div>
      </div>
    `;
  }

  // 添加事件监听器
  stockList.querySelectorAll('.settings-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.preventDefault();
      e.stopPropagation();
      const code = btn.getAttribute('data-code');
      const name = btn.getAttribute('data-name');
      showStockSettings(code, name);
    });
  });

  stockList.querySelectorAll('.delete-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.preventDefault();
      e.stopPropagation();
      const code = btn.getAttribute('data-code');
      removeStock(code);
    });
  });
  
  // 添加量化分析按钮的事件监听
  stockList.querySelectorAll('.quant-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.preventDefault();
      e.stopPropagation();
      const code = btn.getAttribute('data-code');
      const stock = sortedStockData.find(s => s.code === code);
      if (stock) {
        showQuantitativeAdvice(stock);
      }
    });
  });
  
  
  // 更新刷新状态
  updateRefreshStatus();
}

// 删除股票
async function removeStock(code) {
  try {
    const { stocks } = await getStoredStocks();
    const newStocks = stocks.filter(s => s !== code);
    await chrome.storage.local.set({ stocks: newStocks });
    
    // 同时删除该股票的设置信息
    const { settings } = await getStoredStocks();
    delete settings[code];
    await chrome.storage.local.set({ stockSettings: settings });
    
    // 重新加载列表
    loadStockList();
  } catch (error) {
    console.error('删除股票失败:', error);
    if (error.message.includes('Extension context invalidated')) {
      window.location.reload();
      return;
    }
    alert('删除股票失败，请刷新页面后重试');
  }
}

// 将函数添加到全局作用域
window.loadStockList = loadStockList;
window.showQuantitativeAdvice = showQuantitativeAdvice;

// 量化分析函数
function analyzeStock(stock) {
  // 检查股票对象是否有效
  if (!stock || !stock.code) {
    return {
      action: 'neutral',
      message: '无法获取股票数据',
      confidence: 0,
      reasons: ['股票数据无效']
    };
  }

  // 如果没有成本价或持仓数量，使用不同的分析逻辑
  if (!stock.costPrice || !stock.shares || stock.shares === 0) {
    // 模拟获取技术指标数据
    const technicalIndicators = getTechnicalIndicators(stock.code);
    
    // 对于没有持仓的股票，主要基于技术指标进行分析
    let action = 'neutral';
    let message = '';
    let confidence = 0.5;
    let reasons = ['当前无持仓，基于技术指标分析'];
    
    // 技术指标分析
    if (technicalIndicators) {
      // 1. 趋势分析 - 使用多个时间周期的趋势判断
      let trendScore = 0;
      let trendReasons = [];
      
      // 日线趋势
      if (technicalIndicators.dailyTrend) {
        if (technicalIndicators.dailyTrend === 'up') {
          trendScore += 1;
          trendReasons.push('日线呈上升趋势');
        } else if (technicalIndicators.dailyTrend === 'down') {
          trendScore -= 1;
          trendReasons.push('日线呈下降趋势');
        }
      }
      
      // 周线趋势
      if (technicalIndicators.weeklyTrend) {
        if (technicalIndicators.weeklyTrend === 'up') {
          trendScore += 1.5;
          trendReasons.push('周线呈上升趋势');
        } else if (technicalIndicators.weeklyTrend === 'down') {
          trendScore -= 1.5;
          trendReasons.push('周线呈下降趋势');
        }
      }
      
      // 月线趋势
      if (technicalIndicators.monthlyTrend) {
        if (technicalIndicators.monthlyTrend === 'up') {
          trendScore += 2;
          trendReasons.push('月线呈上升趋势');
        } else if (technicalIndicators.monthlyTrend === 'down') {
          trendScore -= 2;
          trendReasons.push('月线呈下降趋势');
        }
      }
      
      // 添加趋势分析结果
      if (trendReasons.length > 0) {
        reasons.push(...trendReasons);
        if (trendScore > 1) {
          confidence += 0.2;
        } else if (trendScore < -1) {
          confidence -= 0.2;
        }
      }
      
      // 2. 均线系统分析
      let maScore = 0;
      let maReasons = [];
      
      // 短期均线
      if (technicalIndicators.ma5 && technicalIndicators.ma10) {
        if (technicalIndicators.ma5 > technicalIndicators.ma10) {
          maScore += 1;
          maReasons.push('5日均线上穿10日均线，短期趋势向好');
        } else if (technicalIndicators.ma5 < technicalIndicators.ma10) {
          maScore -= 1;
          maReasons.push('5日均线下穿10日均线，短期趋势转弱');
        }
      }
      
      // 中期均线
      if (technicalIndicators.ma20 && technicalIndicators.ma60) {
        if (technicalIndicators.ma20 > technicalIndicators.ma60) {
          maScore += 1.5;
          maReasons.push('20日均线上穿60日均线，中期趋势向好');
        } else if (technicalIndicators.ma20 < technicalIndicators.ma60) {
          maScore -= 1.5;
          maReasons.push('20日均线下穿60日均线，中期趋势转弱');
        }
      }
      
      // 长期均线
      if (technicalIndicators.ma120 && technicalIndicators.ma250) {
        if (technicalIndicators.ma120 > technicalIndicators.ma250) {
          maScore += 2;
          maReasons.push('120日均线上穿250日均线，长期趋势向好');
        } else if (technicalIndicators.ma120 < technicalIndicators.ma250) {
          maScore -= 2;
          maReasons.push('120日均线下穿250日均线，长期趋势转弱');
        }
      }
      
      // 添加均线分析结果
      if (maReasons.length > 0) {
        reasons.push(...maReasons);
        if (maScore > 1) {
          confidence += 0.15;
        } else if (maScore < -1) {
          confidence -= 0.15;
        }
      }
      
      // 3. MACD指标分析
      if (technicalIndicators.macd) {
        if (technicalIndicators.macd.signal === 'buy') {
          reasons.push('MACD指标显示买入信号');
          confidence += 0.1;
        } else if (technicalIndicators.macd.signal === 'sell') {
          reasons.push('MACD指标显示卖出信号');
          confidence -= 0.1;
        }
        
        // MACD金叉/死叉
        if (technicalIndicators.macd.cross === 'golden') {
          reasons.push('MACD金叉，买入信号增强');
          confidence += 0.15;
        } else if (technicalIndicators.macd.cross === 'death') {
          reasons.push('MACD死叉，卖出信号增强');
          confidence -= 0.15;
        }
      }
      
      // 4. RSI指标分析
      if (technicalIndicators.rsi) {
        if (technicalIndicators.rsi < 30) {
          reasons.push('RSI指标低于30，处于超卖区域');
          confidence += 0.1;
        } else if (technicalIndicators.rsi > 70) {
          reasons.push('RSI指标高于70，处于超买区域');
          confidence -= 0.1;
        }
        
        // RSI背离
        if (technicalIndicators.rsiDivergence === 'bullish') {
          reasons.push('RSI底背离，可能即将反弹');
          confidence += 0.2;
        } else if (technicalIndicators.rsiDivergence === 'bearish') {
          reasons.push('RSI顶背离，可能即将回调');
          confidence -= 0.2;
        }
      }
      
      // 5. 布林带分析
      if (technicalIndicators.bollinger) {
        if (technicalIndicators.bollinger.position === 'lower') {
          reasons.push('股价触及布林带下轨，可能超卖');
          confidence += 0.1;
        } else if (technicalIndicators.bollinger.position === 'upper') {
          reasons.push('股价触及布林带上轨，可能超买');
          confidence -= 0.1;
        }
        
        // 布林带开口/收口
        if (technicalIndicators.bollinger.width === 'expanding') {
          reasons.push('布林带开口扩大，波动性增加');
          if (trendScore > 0) {
            confidence += 0.1;
          } else {
            confidence -= 0.1;
          }
        } else if (technicalIndicators.bollinger.width === 'contracting') {
          reasons.push('布林带收口，波动性减小');
          if (trendScore > 0) {
            confidence += 0.05;
          } else {
            confidence -= 0.05;
          }
        }
      }
      
      // 6. 成交量分析
      if (technicalIndicators.volume) {
        if (technicalIndicators.volume.trend === 'up') {
          reasons.push('成交量呈上升趋势，交投活跃');
          if (trendScore > 0) {
            confidence += 0.1;
          }
        } else if (technicalIndicators.volume.trend === 'down') {
          reasons.push('成交量呈下降趋势，交投清淡');
          if (trendScore < 0) {
            confidence -= 0.1;
          }
        }
        
        // 量价关系
        if (technicalIndicators.volume.priceRelation === 'price_up_volume_up') {
          reasons.push('价升量增，上涨动能强劲');
          confidence += 0.15;
        } else if (technicalIndicators.volume.priceRelation === 'price_down_volume_up') {
          reasons.push('价跌量增，下跌动能强劲');
          confidence -= 0.15;
        } else if (technicalIndicators.volume.priceRelation === 'price_up_volume_down') {
          reasons.push('价升量减，上涨动能减弱');
          confidence -= 0.1;
        } else if (technicalIndicators.volume.priceRelation === 'price_down_volume_down') {
          reasons.push('价跌量减，下跌动能减弱');
          confidence += 0.1;
        }
      }
      
      // 7. KDJ指标分析
      if (technicalIndicators.kdj) {
        if (technicalIndicators.kdj.signal === 'buy') {
          reasons.push('KDJ指标显示买入信号');
          confidence += 0.1;
        } else if (technicalIndicators.kdj.signal === 'sell') {
          reasons.push('KDJ指标显示卖出信号');
          confidence -= 0.1;
        }
        
        // KDJ金叉/死叉
        if (technicalIndicators.kdj.cross === 'golden') {
          reasons.push('KDJ金叉，买入信号增强');
          confidence += 0.15;
        } else if (technicalIndicators.kdj.cross === 'death') {
          reasons.push('KDJ死叉，卖出信号增强');
          confidence -= 0.15;
        }
      }
      
      // 8. 市场情绪分析
      if (technicalIndicators.marketSentiment) {
        if (technicalIndicators.marketSentiment === 'bullish') {
          reasons.push('市场情绪偏多');
          confidence += 0.1;
        } else if (technicalIndicators.marketSentiment === 'bearish') {
          reasons.push('市场情绪偏空');
          confidence -= 0.1;
        }
      }
    }
    
    // 根据置信度确定最终操作
    if (confidence > 0.7) {
      action = 'buy';
      message = '买入建议: 技术指标显示较好的买入机会';
    } else if (confidence < 0.3) {
      action = 'neutral';
      message = '观望建议: 技术指标显示当前不适合买入';
    } else {
      action = 'neutral';
      message = '观望建议: 技术指标显示中性，可继续观察';
    }
    
    return {
      action,
      message,
      confidence,
      reasons
    };
  }

  // 有持仓的股票分析逻辑
  const currentPrice = stock.price;
  const costPrice = stock.costPrice;
  const profitPercent = ((currentPrice - costPrice) / costPrice * 100);
  
  // 模拟获取技术指标数据
  const technicalIndicators = getTechnicalIndicators(stock.code);
  
  // 量化策略
  let action = 'neutral';
  let message = '';
  let confidence = 0;
  let reasons = [];
  
  // 1. 止损策略 - 亏损超过5%建议卖出
  if (profitPercent < -5) {
    action = 'sell';
    message = '止损建议: 当前亏损超过5%，建议考虑卖出';
    confidence = Math.min(Math.abs(profitPercent) / 5, 1) * 0.8;
    reasons.push('亏损超过5%');
  }
  // 2. 止盈策略 - 盈利超过10%建议卖出
  else if (profitPercent > 10) {
    action = 'sell';
    message = '止盈建议: 当前盈利超过10%，建议考虑卖出';
    confidence = Math.min(profitPercent / 10, 1) * 0.7;
    reasons.push('盈利超过10%');
  }
  // 3. 买入策略 - 价格低于成本价5%以上，且有上涨趋势
  else if (profitPercent < -5 && stock.change > 0) {
    action = 'buy';
    message = '买入建议: 价格低于成本价且开始上涨，可考虑加仓';
    confidence = 0.6;
    reasons.push('价格低于成本价且开始上涨');
  }
  // 4. 持有策略 - 盈利在5%-10%之间，且仍在上涨
  else if (profitPercent > 5 && profitPercent < 10 && stock.change > 0) {
    action = 'hold';
    message = '持有建议: 当前盈利良好且仍在上涨，建议继续持有';
    confidence = 0.7;
    reasons.push('盈利良好且仍在上涨');
  }
  // 默认策略
  else {
    action = 'hold';
    message = '持有建议: 当前无明确信号，建议继续持有';
    confidence = 0.5;
    reasons.push('无明确信号');
  }
  
  // 技术指标分析
  if (technicalIndicators) {
    // 1. 趋势分析
    let trendScore = 0;
    let trendReasons = [];
    
    // 日线趋势
    if (technicalIndicators.dailyTrend) {
      if (technicalIndicators.dailyTrend === 'up') {
        trendScore += 1;
        trendReasons.push('日线呈上升趋势');
      } else if (technicalIndicators.dailyTrend === 'down') {
        trendScore -= 1;
        trendReasons.push('日线呈下降趋势');
      }
    }
    
    // 周线趋势
    if (technicalIndicators.weeklyTrend) {
      if (technicalIndicators.weeklyTrend === 'up') {
        trendScore += 1.5;
        trendReasons.push('周线呈上升趋势');
      } else if (technicalIndicators.weeklyTrend === 'down') {
        trendScore -= 1.5;
        trendReasons.push('周线呈下降趋势');
      }
    }
    
    // 月线趋势
    if (technicalIndicators.monthlyTrend) {
      if (technicalIndicators.monthlyTrend === 'up') {
        trendScore += 2;
        trendReasons.push('月线呈上升趋势');
      } else if (technicalIndicators.monthlyTrend === 'down') {
        trendScore -= 2;
        trendReasons.push('月线呈下降趋势');
      }
    }
    
    // 添加趋势分析结果
    if (trendReasons.length > 0) {
      reasons.push(...trendReasons);
      if (action === 'buy' && trendScore > 1) {
        confidence += 0.2;
      } else if (action === 'sell' && trendScore < -1) {
        confidence += 0.2;
      } else if (action === 'buy' && trendScore < -1) {
        confidence -= 0.2;
      } else if (action === 'sell' && trendScore > 1) {
        confidence -= 0.2;
      }
    }
    
    // 2. 均线系统分析
    let maScore = 0;
    let maReasons = [];
    
    // 短期均线
    if (technicalIndicators.ma5 && technicalIndicators.ma10) {
      if (technicalIndicators.ma5 > technicalIndicators.ma10) {
        maScore += 1;
        maReasons.push('5日均线上穿10日均线，短期趋势向好');
      } else if (technicalIndicators.ma5 < technicalIndicators.ma10) {
        maScore -= 1;
        maReasons.push('5日均线下穿10日均线，短期趋势转弱');
      }
    }
    
    // 中期均线
    if (technicalIndicators.ma20 && technicalIndicators.ma60) {
      if (technicalIndicators.ma20 > technicalIndicators.ma60) {
        maScore += 1.5;
        maReasons.push('20日均线上穿60日均线，中期趋势向好');
      } else if (technicalIndicators.ma20 < technicalIndicators.ma60) {
        maScore -= 1.5;
        maReasons.push('20日均线下穿60日均线，中期趋势转弱');
      }
    }
    
    // 长期均线
    if (technicalIndicators.ma120 && technicalIndicators.ma250) {
      if (technicalIndicators.ma120 > technicalIndicators.ma250) {
        maScore += 2;
        maReasons.push('120日均线上穿250日均线，长期趋势向好');
      } else if (technicalIndicators.ma120 < technicalIndicators.ma250) {
        maScore -= 2;
        maReasons.push('120日均线下穿250日均线，长期趋势转弱');
      }
    }
    
    // 添加均线分析结果
    if (maReasons.length > 0) {
      reasons.push(...maReasons);
      if (action === 'buy' && maScore > 1) {
        confidence += 0.15;
      } else if (action === 'sell' && maScore < -1) {
        confidence += 0.15;
      } else if (action === 'buy' && maScore < -1) {
        confidence -= 0.15;
      } else if (action === 'sell' && maScore > 1) {
        confidence -= 0.15;
      }
    }
    
    // 3. MACD指标分析
    if (technicalIndicators.macd) {
      if (technicalIndicators.macd.signal === 'buy') {
        reasons.push('MACD指标显示买入信号');
        if (action === 'buy') confidence += 0.1;
      } else if (technicalIndicators.macd.signal === 'sell') {
        reasons.push('MACD指标显示卖出信号');
        if (action === 'sell') confidence += 0.1;
      }
      
      // MACD金叉/死叉
      if (technicalIndicators.macd.cross === 'golden') {
        reasons.push('MACD金叉，买入信号增强');
        if (action === 'buy') confidence += 0.15;
      } else if (technicalIndicators.macd.cross === 'death') {
        reasons.push('MACD死叉，卖出信号增强');
        if (action === 'sell') confidence += 0.15;
      }
    }
    
    // 4. RSI指标分析
    if (technicalIndicators.rsi) {
      if (technicalIndicators.rsi < 30) {
        reasons.push('RSI指标低于30，处于超卖区域');
        if (action === 'buy') confidence += 0.1;
      } else if (technicalIndicators.rsi > 70) {
        reasons.push('RSI指标高于70，处于超买区域');
        if (action === 'sell') confidence += 0.1;
      }
      
      // RSI背离
      if (technicalIndicators.rsiDivergence === 'bullish') {
        reasons.push('RSI底背离，可能即将反弹');
        if (action === 'buy') confidence += 0.2;
      } else if (technicalIndicators.rsiDivergence === 'bearish') {
        reasons.push('RSI顶背离，可能即将回调');
        if (action === 'sell') confidence += 0.2;
      }
    }
    
    // 5. 布林带分析
    if (technicalIndicators.bollinger) {
      if (technicalIndicators.bollinger.position === 'lower') {
        reasons.push('股价触及布林带下轨，可能超卖');
        if (action === 'buy') confidence += 0.1;
      } else if (technicalIndicators.bollinger.position === 'upper') {
        reasons.push('股价触及布林带上轨，可能超买');
        if (action === 'sell') confidence += 0.1;
      }
      
      // 布林带开口/收口
      if (technicalIndicators.bollinger.width === 'expanding') {
        reasons.push('布林带开口扩大，波动性增加');
        if (action === 'buy' && trendScore > 0) {
          confidence += 0.1;
        } else if (action === 'sell' && trendScore < 0) {
          confidence += 0.1;
        }
      } else if (technicalIndicators.bollinger.width === 'contracting') {
        reasons.push('布林带收口，波动性减小');
        if (action === 'buy' && trendScore > 0) {
          confidence += 0.05;
        } else if (action === 'sell' && trendScore < 0) {
          confidence += 0.05;
        }
      }
    }
    
    // 6. 成交量分析
    if (technicalIndicators.volume) {
      if (technicalIndicators.volume.trend === 'up') {
        reasons.push('成交量呈上升趋势，交投活跃');
        if (action === 'buy' && trendScore > 0) {
          confidence += 0.1;
        } else if (action === 'sell' && trendScore < 0) {
          confidence += 0.1;
        }
      } else if (technicalIndicators.volume.trend === 'down') {
        reasons.push('成交量呈下降趋势，交投清淡');
        if (action === 'buy' && trendScore > 0) {
          confidence -= 0.1;
        } else if (action === 'sell' && trendScore < 0) {
          confidence -= 0.1;
        }
      }
      
      // 量价关系
      if (technicalIndicators.volume.priceRelation === 'price_up_volume_up') {
        reasons.push('价升量增，上涨动能强劲');
        if (action === 'buy') confidence += 0.15;
      } else if (technicalIndicators.volume.priceRelation === 'price_down_volume_up') {
        reasons.push('价跌量增，下跌动能强劲');
        if (action === 'sell') confidence += 0.15;
      } else if (technicalIndicators.volume.priceRelation === 'price_up_volume_down') {
        reasons.push('价升量减，上涨动能减弱');
        if (action === 'buy') confidence -= 0.1;
      } else if (technicalIndicators.volume.priceRelation === 'price_down_volume_down') {
        reasons.push('价跌量减，下跌动能减弱');
        if (action === 'sell') confidence -= 0.1;
      }
    }
    
    // 7. KDJ指标分析
    if (technicalIndicators.kdj) {
      if (technicalIndicators.kdj.signal === 'buy') {
        reasons.push('KDJ指标显示买入信号');
        if (action === 'buy') confidence += 0.1;
      } else if (technicalIndicators.kdj.signal === 'sell') {
        reasons.push('KDJ指标显示卖出信号');
        if (action === 'sell') confidence += 0.1;
      }
      
      // KDJ金叉/死叉
      if (technicalIndicators.kdj.cross === 'golden') {
        reasons.push('KDJ金叉，买入信号增强');
        if (action === 'buy') confidence += 0.15;
      } else if (technicalIndicators.kdj.cross === 'death') {
        reasons.push('KDJ死叉，卖出信号增强');
        if (action === 'sell') confidence += 0.15;
      }
    }
    
    // 8. 市场情绪分析
    if (technicalIndicators.marketSentiment) {
      if (technicalIndicators.marketSentiment === 'bullish') {
        reasons.push('市场情绪偏多');
        if (action === 'buy') confidence += 0.1;
      } else if (technicalIndicators.marketSentiment === 'bearish') {
        reasons.push('市场情绪偏空');
        if (action === 'sell') confidence += 0.1;
      }
    }
  }
  
  // 确保置信度不超过1
  confidence = Math.min(confidence, 1);
  
  return {
    action,
    message,
    confidence,
    reasons
  };
}

// 模拟获取技术指标数据
function getTechnicalIndicators(code) {
  // 在实际应用中，这些数据应该从API获取
  // 这里使用随机数据模拟
  
  // 由于无法直接获取当前价格，使用随机值模拟
  // 在实际应用中，应该从API获取真实数据
  const ma5 = Math.random() * 100;
  const ma10 = Math.random() * 100;
  const ma20 = Math.random() * 100;
  const ma60 = Math.random() * 100;
  const ma120 = Math.random() * 100;
  const ma250 = Math.random() * 100;
  
  // 随机生成趋势
  const trends = ['up', 'down', 'sideways'];
  const dailyTrend = trends[Math.floor(Math.random() * trends.length)];
  const weeklyTrend = trends[Math.floor(Math.random() * trends.length)];
  const monthlyTrend = trends[Math.floor(Math.random() * trends.length)];
  
  // 随机生成RSI指标
  const rsi = 30 + Math.random() * 50;
  
  // 随机生成RSI背离
  const divergences = ['bullish', 'bearish', null];
  const rsiDivergence = divergences[Math.floor(Math.random() * divergences.length)];
  
  // 随机生成MACD信号
  const macdSignals = ['buy', 'sell', 'neutral'];
  const macdSignal = macdSignals[Math.floor(Math.random() * macdSignals.length)];
  
  // 随机生成MACD金叉/死叉
  const macdCrosses = ['golden', 'death', null];
  const macdCross = macdCrosses[Math.floor(Math.random() * macdCrosses.length)];
  
  // 随机生成布林带位置
  const bollingerPositions = ['upper', 'middle', 'lower'];
  const bollingerPosition = bollingerPositions[Math.floor(Math.random() * bollingerPositions.length)];
  
  // 随机生成布林带宽度
  const bollingerWidths = ['expanding', 'contracting', 'stable'];
  const bollingerWidth = bollingerWidths[Math.floor(Math.random() * bollingerWidths.length)];
  
  // 随机生成成交量趋势
  const volumeTrends = ['up', 'down', 'stable'];
  const volumeTrend = volumeTrends[Math.floor(Math.random() * volumeTrends.length)];
  
  // 随机生成量价关系
  const priceRelations = ['price_up_volume_up', 'price_up_volume_down', 'price_down_volume_up', 'price_down_volume_down'];
  const priceRelation = priceRelations[Math.floor(Math.random() * priceRelations.length)];
  
  // 随机生成KDJ信号
  const kdjSignals = ['buy', 'sell', 'neutral'];
  const kdjSignal = kdjSignals[Math.floor(Math.random() * kdjSignals.length)];
  
  // 随机生成KDJ金叉/死叉
  const kdjCrosses = ['golden', 'death', null];
  const kdjCross = kdjCrosses[Math.floor(Math.random() * kdjCrosses.length)];
  
  // 随机生成市场情绪
  const marketSentiments = ['bullish', 'bearish', 'neutral'];
  const marketSentiment = marketSentiments[Math.floor(Math.random() * marketSentiments.length)];
  
  return {
    ma5,
    ma10,
    ma20,
    ma60,
    ma120,
    ma250,
    dailyTrend,
    weeklyTrend,
    monthlyTrend,
    rsi,
    rsiDivergence,
    macd: {
      signal: macdSignal,
      cross: macdCross
    },
    bollinger: {
      position: bollingerPosition,
      width: bollingerWidth
    },
    volume: {
      trend: volumeTrend,
      priceRelation: priceRelation
    },
    kdj: {
      signal: kdjSignal,
      cross: kdjCross
    },
    marketSentiment
  };
}

// 显示量化推荐操作
function showQuantitativeAdvice(stock) {
  // 使用已存储的分析结果，而不是重新分析
  const analysis = stock.quantitativeAnalysis || analyzeStock(stock);
  
  // 创建推荐面板
  const advicePanel = document.createElement('div');
  advicePanel.className = 'quantitative-advice-panel';
  
  // 根据推荐操作设置不同的样式
  const actionClass = analysis.action;
  const confidencePercent = Math.round(analysis.confidence * 100);
  
  // 生成原因列表HTML
  const reasonsHtml = analysis.reasons.map(reason => `<li>${reason}</li>`).join('');
  
  advicePanel.innerHTML = `
    <div class="advice-content">
      <h3>量化分析 - ${stock.name} (${stock.code})</h3>
      <div class="advice-action ${actionClass}">
        <span class="action-icon">${getActionIcon(analysis.action)}</span>
        <span class="action-text">${getActionText(analysis.action)}</span>
        <span class="confidence">置信度: ${confidencePercent}%</span>
      </div>
      <div class="advice-message">${analysis.message}</div>
      <div class="advice-reasons">
        <h4>分析依据:</h4>
        <ul>${reasonsHtml}</ul>
      </div>
      <div class="advice-details">
        <div>当前价格: ${stock.price.toFixed(2)}</div>
        <div>成本价格: ${stock.costPrice.toFixed(2)}</div>
        <div>盈亏比例: ${((stock.price - stock.costPrice) / stock.costPrice * 100).toFixed(2)}%</div>
        <div>持仓数量: ${(stock.shares / 100).toFixed(0)}手</div>
      </div>
      <div class="advice-actions">
        <button class="close-btn">关闭</button>
      </div>
    </div>
  `;
  
  // 添加关闭事件
  advicePanel.querySelector('.close-btn').addEventListener('click', () => {
    advicePanel.remove();
  });
  
  // 添加点击空白区域关闭事件
  advicePanel.addEventListener('click', (e) => {
    // 如果点击的是面板本身（而不是内容区域），则关闭面板
    if (e.target === advicePanel) {
      advicePanel.remove();
    }
  });
  
  // 添加到页面
  document.body.appendChild(advicePanel);
}

// 获取操作图标
function getActionIcon(action) {
  switch (action) {
    case 'buy': return '📈';
    case 'sell': return '📉';
    case 'hold': return '⏳';
    default: return '❓';
  }
}

// 获取操作文本
function getActionText(action) {
  switch (action) {
    case 'buy': return '买入';
    case 'sell': return '卖出';
    case 'hold': return '持有';
    default: return '观望';
  }
}

// 添加KIMI AI按钮事件监听
function initKimiAiButton() {
  const kimiAiBtn = document.getElementById('kimiAiBtn');
  if (kimiAiBtn) {
    kimiAiBtn.addEventListener('click', () => {
      const url = 'https://kimi.moonshot.cn/';
      window.open(url, '_blank');
    });
  }
}

// 确保在DOM加载完成后添加事件监听
document.addEventListener('DOMContentLoaded', () => {
  initKimiAiButton();
});

// 在openSettings函数中也需要初始化按钮
function openSettings() {
  // 移除可能存在的旧面板
  closeSettings();
  
  // 创建遮罩层
  const overlay = document.createElement('div');
  overlay.className = 'settings-overlay';
  overlay.onclick = closeSettings;
  document.body.appendChild(overlay);
  
  // 创建设置面板
  const settingsPanel = document.createElement('div');
  settingsPanel.className = 'settings-panel';
  settingsPanel.innerHTML = `
    <div class="settings-content">
      <h3>STOCK</h3>
      <div class="stock-input">
        <input type="text" id="stockCode" placeholder="输入6位股票代码" maxlength="6" autocomplete="off">
        <button id="addStockBtn">添加</button>
        <button id="kimiAiBtn">KIMI AI</button>
        <div class="stock-summary">
          <div class="summary-item">
            <span class="summary-label">总成本</span>
            <span class="summary-value" id="totalCost">0.00</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">总盈利</span>
            <span class="summary-value" id="totalProfit">0.00 <span class="summary-percent">0.00%</span></span>
          </div>
        </div>
      </div>
      <div class="refresh-status">
        <span class="last-refresh">最后刷新：--:--:--</span>
        <span class="market-status"></span>
      </div>
      <div id="stockList"></div>
    </div>
  `;
  
  // 先添加面板，再加载数据
  document.body.appendChild(settingsPanel);
  
  // 加载数据
  loadStockList();
  
  // 添加输入监听
  const input = settingsPanel.querySelector('#stockCode');
  const addButton = settingsPanel.querySelector('#addStockBtn');
  
  // 限制只能输入数字
  input.addEventListener('input', (e) => {
    e.target.value = e.target.value.replace(/[^\d]/g, '');
  });
  
  // 添加按钮点击事件
  addButton.addEventListener('click', () => addStock());
  
  // 输入框回车事件
  input.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      addStock();
    }
  });

  // 添加遮罩层点击事件
  overlay.addEventListener('click', (e) => {
    if (e.target === overlay) {
      closeSettings();
    }
  });
  
  // 更新刷新状态
  updateRefreshStatus();
  
  // 初始化KIMI AI按钮
  initKimiAiButton();
}
